package com.zhika.zishi.fragments.set;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zhika.zishi.MyApplication;
import com.zhika.zishi.R;
import com.zhika.zishi.activity.MainActivity;
import com.zhika.zishi.constant.InternetConstant;
import com.zhika.zishi.customview.TitleView;
import com.zhika.zishi.db.OperateDb;
import com.zhika.zishi.interfaces.TitleInterface;
import com.zhika.zishi.util.ActivityCollector;
import com.zhika.zishi.util.LogUtil;

import org.apache.http.Header;
import org.json.JSONObject;

/**
 * Created by shi-02 on 2015/4/18.
 */
public class SettingFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = "SettingActivity";

    private TitleView titleView;

    private RelativeLayout myselfLayout;

    private RelativeLayout secureLayout;

    private RelativeLayout remindLayout;

    private RelativeLayout saidLayout;

    private RelativeLayout aboutLayout;

    private Button quitButton;

    //退出时，返回给handler时，传的what
    private static final int QUIT = 1;

    //网络请求对象
    private AsyncHttpClient asyncHttpClient;

    //操作数据库的对象
    private OperateDb operateDb;
    
    private View view;
    
    private Context context;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case QUIT:
                    if (msg.arg1 == 1) {
                        MyApplication.showToast("成功退出");

                        //2--已退出
                        operateDb.updateIsLoginState(MyApplication.userId,2);
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("intent","login");
                        startActivity(intent);
                        ActivityCollector.finishAllActivity();
                    } else {
                        MyApplication.showToast("退出失败");
                    }
                    break;
            }
        }
    };
 
    public interface OnSettingInterfer{
        
        //销毁此Activity
        public void finishActivity();

        //个人资料更改
        public void settingMyselfInfo();

        //type: secure代表隐私与安全；remind 代表提醒与通知
        public void secureRemind(String type);

        //吐槽我们
        public void saidUs();

        //关于我们
        public void aboutUs();


    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.setting_layout,container,false);
        initView();
        return view;
    }

    private void initView() {

        context = getActivity();
        
        //实例化操作数据库的对象
        operateDb = new OperateDb(context);


        //实例化网络请求对象
        asyncHttpClient = new AsyncHttpClient();

        titleView = (TitleView) view.findViewById(R.id.setting_title_view);
        titleView.setLeftButtonText("返回");
        titleView.setMiddleRowText("设置");
        titleView.hideRightButton();
        titleView.setTitleViewInterface(new TitleInterface() {
            @Override
            public void leftTitleListener() {
                ((OnSettingInterfer)context).finishActivity();
            }

            @Override
            public void middleTitleListener() {

            }

            @Override
            public void rightTitleListener() {

            }
        });

        myselfLayout = (RelativeLayout) view.findViewById(R.id.setting_myself_layout);
        myselfLayout.setOnClickListener(this);

        secureLayout = (RelativeLayout) view.findViewById(R.id.setting_secure_layout);
        secureLayout.setOnClickListener(this);

        remindLayout = (RelativeLayout) view.findViewById(R.id.setting_remind_layout);
        remindLayout.setOnClickListener(this);

        saidLayout = (RelativeLayout) view.findViewById(R.id.setting_said_layout);
        saidLayout.setOnClickListener(this);

        aboutLayout = (RelativeLayout) view.findViewById(R.id.setting_about_layout);
        aboutLayout.setOnClickListener(this);

        quitButton = (Button) view.findViewById(R.id.setting_quit_button);
        quitButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_myself_layout:
                ((OnSettingInterfer)context).settingMyselfInfo();
                break;
            case R.id.setting_secure_layout:
                ((OnSettingInterfer)context).secureRemind("secure");
                break;
            case R.id.setting_remind_layout:
                ((OnSettingInterfer)context).secureRemind("remind");
                break;
            case R.id.setting_said_layout:
                ((OnSettingInterfer)context).saidUs();
                break;
            case R.id.setting_about_layout:
                ((OnSettingInterfer)context).aboutUs();
                break;
            case R.id.setting_quit_button:
                quitButtonListener();
                break;
            default:
                break;
        }
    }
    /**
     * 退出登录的事件
     */
    private void quitButtonListener() {
        String url = InternetConstant.SERVER_ADDRESS + InternetConstant.QUIT_LOGIN+"?uid="
                +MyApplication.userId+"&token="+MyApplication.token+"&deviceTag="+MyApplication.device_id;

        LogUtil.e(TAG, "退出登录-url：" + url);

        asyncHttpClient.post(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                LogUtil.e(TAG, "退出登录-成功返回码：code=" + i);
                String jsonData = new String(bytes);
                LogUtil.e(TAG, "退出登录-成功：" + jsonData);

                //解析json
                parseQuitJsonData(jsonData);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                LogUtil.e(TAG, "退出登录-错误：code=" + i);
                throwable.printStackTrace();
            }
        });

    }

    /**
     * 解析退出登录接口返回的json数据
     *
     * @param jsonData
     */
    private void parseQuitJsonData(String jsonData) {

        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            boolean isSuccess = jsonObject.getBoolean("success");

            Message message = Message.obtain();
            message.what = QUIT;

            //退出成功
            if (isSuccess) {
                message.arg1 = 1;
            }
            //退出失败
            else {
                message.arg1 = 2;
            }
            handler.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
